<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--树结构-->
      <el-col :span="4" :xs="24">
        <div class="app-container-tree-border">
          <el-tree
            :data="syTypeList"
            :props="defaultProps"
            :expand-on-click-node="false"
            ref="tree"
            node-key="id"
            highlight-current
            @node-click="handleNodeClick"
            :default-expand-all="defaultExpandAll"
          >
            <div slot-scope="{ node, data }" class="custom-tree-node" :title="node.label" v-text="node.label"></div>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <div class="app-container-table-border">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="0px" class="top-left">
            <!-- <el-form-item label prop="reportName">
              <el-input v-model="queryParams.reportName" placeholder="请输入试验名称" clearable
                @keyup.enter.native="handleQuery" style="width: 180px;" />
            </el-form-item> -->
            <el-form-item label prop="reportDate">
              <!-- <el-date-picker clearable v-model="queryParams.reportDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择试验日期" style="width: 180px;"></el-date-picker> -->
              <el-date-picker
                v-model="dateRange"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="～"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <!-- <el-form-item label="" prop="bgCode">
            <el-input v-model="queryParams.bgCode" placeholder="请输入报告编号" clearable
              @keyup.enter.native="handleQuery" />
            </el-form-item>-->
            <el-form-item label prop="ypCode">
              <el-input v-model="queryParams.ypCode" placeholder="请输入样品编号" clearable @keyup.enter.native="handleQuery" style="width: 180px" />
            </el-form-item>
            <!-- <el-form-item label="记录编号" prop="jlCode">
            <el-input v-model="queryParams.jlCode" placeholder="请输入记录编号" clearable
              @keyup.enter.native="handleQuery" />
            </el-form-item>-->

            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb5 top-right-btn small-line-height">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['syrw:bsDataReport:add']" v-if="canUpdate()">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['syrw:bsDataReport:edit']" v-if="canUpdate()">修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['syrw:bsDataReport:remove']" v-if="canUpdate()">删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain icon="el-icon-download" size="mini" :disabled="single" v-hasPermi="['syrw:bsDataReport:tb']" @click="onExport">导出</el-button>
            </el-col>
            <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
          </el-row>

          <el-table border stripe v-loading="loading" :data="bsDataReportList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="唯一标识一份试验任务" align="center" prop="reportId" v-if="false" />
            <el-table-column label="所属试验类型" align="center" prop="syTypeStr" min-width="180" show-overflow-tooltip />
            <el-table-column label="所属试验室id" align="center" prop="deptId" v-if="false" />
            <el-table-column label="样品名称" align="center" prop="ypVo.yangpmc" min-width="160" show-overflow-tooltip />
            <el-table-column label="试验日期" align="center" prop="shiyrqLabel" width="250" />
            <el-table-column label="报告编号" align="center" prop="bgCode" min-width="180" show-overflow-tooltip v-if="false" />
            <el-table-column label="样品编号" align="center" prop="ypCode" min-width="180" show-overflow-tooltip />
            <el-table-column label="检测项目" align="center" prop="jiancxm" min-width="180" show-overflow-tooltip />
            <el-table-column label="检测结果" align="center" prop="reportResult" min-width="80">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.report_result" :value="scope.row.reportResult" />
              </template>
            </el-table-column>
            <el-table-column label="所属合同id" align="center" prop="contractId" v-if="false" />
            <el-table-column label="包含excel份数" align="center" prop="excelNums" width="116" show-overflow-tooltip v-if="false" />
            <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="180">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="查看" placement="bottom" :open-delay="600">
                  <el-button size="mini" type="text" icon="el-icon-view" @click="handleUpdate(scope.row, true)" v-hasPermi="['syrw:bsDataReport:edit']"></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="修改" placement="bottom" :open-delay="600">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['syrw:bsDataReport:edit']" v-if="canUpdate()"></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="填报" placement="bottom" :open-delay="600">
                  <el-button size="mini" type="text" icon="el-icon-edit-outline" @click="handleTb(scope.row)" v-hasPermi="['syrw:bsDataReport:tb']" v-if="canUpdate()"></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="复制" placement="bottom" :open-delay="600">
                  <el-button size="mini" type="text" icon="el-icon-document-copy" @click="handleCopy(scope.row)" v-hasPermi="['syrw:bsDataReport:copy']" v-if="canUpdate()"></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="附件" placement="bottom" :open-delay="600">
                  <el-button size="mini" type="text" @click="onUploadFile(scope.row)" v-hasPermi="['syrw:bsDataReport:copy']">
                    <span class="iconfont icon-shangchuanfujian"></span>
                  </el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="导出" placement="bottom" :open-delay="600">
                  <el-button size="mini" type="text" @click="onExport(scope.row)" v-hasPermi="['syrw:bsDataReport:tb']">
                    <span class="iconfont icon-xiazai2"></span>
                  </el-button>
                </el-tooltip>

                <!--                需求不安全，暂时下线二维码功能-->
                <!--                <el-tooltip class="item" effect="dark" content="二维码" placement="bottom" :open-delay="600">-->
                <!--                  <el-button size="mini" type="text" @click="getQrcode(scope.row)"-->
                <!--                    v-hasPermi="['syrw:bsDataReport:copy']">-->
                <!--                    <span class="iconfont icon-erweima"></span>-->
                <!--                  </el-button>-->
                <!--                </el-tooltip>-->

                <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['syrw:bsDataReport:remove']">删除
                </el-button>-->

                <el-tooltip class="item" effect="dark" content="试验标记" placement="bottom" :open-delay="600">
                  <el-button size="mini" type="text" icon="el-icon-news" @click="handelSYbj(scope.row)" v-hasPermi="['syrw:bsDataReport:sybj']" v-if="canUpdate()"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
      </el-col>
    </el-row>
    <bs-data-report-add-or-update ref="bsDataReportAddOrUpdateRef" :syTypeList="syTypeList" :syType="form.syType" :deptList="deptList" @callBack="handleQuery()" />
    <qrcode-view ref="qrcodeViewRef" />
    <testMarkView ref="testMarkViewRef" />
    <bs-data-report-export ref="bsDataReportExportRef" />
    <file-upload-view ref="fileUploadViewRef" :isReadonly="canUpdate()" :moduleKey="'syrw'" />
  </div>
</template>

<script>
import { listBsDataReport, delBsDataReport, getBsDataReportQrcode, getBsDataReport } from "@/api/syrw/bsDataReport";
import { mapGetters } from "vuex";
import { syTpyeTree } from "@/api/base/syType";
import { deptTreeSelect } from "@/api/system/user";
import BsDataReportAddOrUpdate from "./BsDataReportAddOrUpdate.vue";
import QrcodeView from "./QrcodeView.vue";
import testMarkView from "./testMarkView.vue";
import BsDataReportExport from "./BsDataReportExport.vue";
import { getReportName } from "@/utils/report";
import Bus from "@/utils/bus";
import FileUploadView from "@/components/FileUpload/FileUploadView.vue";

export default {
  components: {
    BsDataReportAddOrUpdate,
    QrcodeView,
    BsDataReportExport,
    FileUploadView,
    testMarkView
  },
  name: "BsDataReport",
  dicts: ["yp_status", "report_result"],
  data() {
    return {
      defaultExpandAll: true,
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 试验类型列表
      syTypeList: [],
      // 试验室列表v
      deptList: [],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 日期范围
      dateRange: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据报告表格数据
      bsDataReportList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        syType: undefined,
        deptId: undefined,
        reportName: undefined,
        reportDate: undefined,
        bgCode: undefined,
        ypCode: undefined,
        jlCode: undefined,
        contractId: undefined,
        excelNums: undefined
      },
      // 表单参数
      form: {
        syType: undefined
      }
    };
  },
  // 监听顶部全局下拉
  computed: {
    ...mapGetters(["deptId", "userDeptId"])
  },
  watch: {
    deptId(newValue, oldValue) {
      this.queryParams.deptId = newValue;
      if (this.queryParams.syType) {
        this.getList();
      }
    }
  },
  created() {
    this.queryParams.deptId = this.$store.state.dept.deptId;
    this.getSyTypeTreeList();
    this.getDeptTreeList();
    // Url传值处理
    // 不合格台账跳转传值
    const syType = this.$route.query && this.$route.query.syType;
    const ypCode = this.$route.query && this.$route.query.ypCode;
    this.routeQueryDispose({ syType, ypCode });
  },
  mounted() {
    // 给试验任务传值
    Bus.$on("setBsDataReport", (data) => {
      this.routeQueryDispose(data);
    });
  },
  methods: {
    routeQueryDispose(data) {
      const { syType, ypCode } = data;
      if (syType && ypCode) {
        this.queryParams.syType = syType;
        this.queryParams.ypCode = ypCode;
        this.form.syType = syType;

        // 选中左侧树
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(syType);
          this.defaultExpandAll = true;
        });
        // 调用右侧列表接口
        this.handleQuery();
      }
    },
    handleNodeClick(data) {
      this.form.syType = undefined;
      this.queryParams.syType = undefined;

      if (data.level == 2) {
        this.queryParams.syType = data.id;
        this.form.syType = data.id;
        this.handleQuery();
      }
    },
    /** 查询试验类型树 */
    getSyTypeTreeList() {
      let param = {
        level: 2,
        innerFlag: "1"
      };
      syTpyeTree(param).then((response) => {
        this.syTypeList = response.data;
        // 选中左侧树
        this.$nextTick(() => {
          if (this.queryParams.syType) {
            this.$refs.tree.setCurrentKey(this.queryParams.syType);
          }
        });
      });
    },
    getDeptTreeList() {
      let param = {
        // labFlag: "1",
        // param: this.queryParams.deptId
      };
      deptTreeSelect(param).then((response) => {
        this.deptList = response.data;
      });
    },
    /** 查询数据报告列表 */
    getList() {
      if (!this.queryParams.deptId) {
        this.$message.error("请先选择一个试验室");
        return;
      }

      if (!this.queryParams.syType) {
        this.$message.warning("请选择一个合法的试验类型");
        return;
      }
      this.loading = true;
      listBsDataReport(this.addDateRange(this.queryParams, this.dateRange, "ReportDate")).then((response) => {
        this.bsDataReportList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.reportId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (!this.queryParams.syType) {
        this.$message.warning("请先选择一个合法的试验类型");
        return;
      }
      this.$refs.bsDataReportAddOrUpdateRef.init();
    },
    /** 修改按钮操作 */
    handleUpdate(row, isView) {
      const reportId = row.reportId || this.ids;
      this.$refs.bsDataReportAddOrUpdateRef.init(reportId, isView);
    },
    // 填报
    handleTb(row) {
      // 获取报表名称
      const name = getReportName(row.syType);
      if (name === "") {
        this.$message.error("没有对应可跳转的页面");
        return;
      }

      this.$message.success("跳转到报表页面，根据row.excelTypeList来动态展示某些Excel");
      const { href } = this.$router.resolve({
        name: name,
        query: {
          t: new Date().getTime(),
          reportId: row.reportId,
          deptId: row.deptId
        }
      });
      window.open(href, "_blank");
    },
    // 复制
    handleCopy(row) {
      // this.$message.success("调用后台接口实现")
      const reportId = row.reportId || this.ids;
      this.$refs.bsDataReportAddOrUpdateRef.onCopy(reportId);
    },
    onLoading() {
      this.$message({
        showClose: true,
        message: "正在开发中..."
      });
    },
    // 导出
    onExport(row) {
      const reportId = row.reportId || this.ids;
      this.$refs.bsDataReportExportRef.init(reportId);
    },
    // 获取二维码
    getQrcode(row) {
      getBsDataReportQrcode(row.reportId).then((res) => {
        if (!res.data || !res.data.url) {
          this.$message.warning("二维码生成失败，请检查是否存在报告");
          return;
        }
        this.$refs.qrcodeViewRef.init(res.data.url);
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const reportIds = row.reportId || this.ids;
      this.$modal
        .confirm('是否确认删除数据报告编号为"' + reportIds + '"的数据项？')
        .then(() => {
          this.loading = true;
          return delBsDataReport(reportIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    // 附件上传
    onUploadFile(row) {
      this.$refs.fileUploadViewRef.init(row.reportId);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "syrw/bsDataReport/export",
        {
          ...this.queryParams
        },
        `bsDataReport_${new Date().getTime()}.xlsx`
      );
    },
    //试验标记按钮操作
    handelSYbj(row) {
      if (row.syTypeStr == "路基路面压实度试验" || row.syTypeStr == "混凝土结构试验") {
        this.$refs.testMarkViewRef.init(row);
      } else {
        this.$message.info("该试验类型暂不支持试验标记功能");
      }
    },
    // 判断用户组织是否和选中的组织一致
    canUpdate() {
      return this.userDeptId === this.deptId;
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/demo.scss";

.table-add {
  text-align: center;
  line-height: 23px;
  padding: 4px;
  border: 1px solid #dfe6ec;
  border-top: 0px solid #dfe6ec;
}
</style>
